// server/app/model/purchase_order_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, DECIMAL, TEXT } = app.Sequelize;

  const PurchaseOrder = app.model.define('purchase_order', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    orderNumber: {
      type: STRING(50),
      allowNull: false,
      unique: true,
      field: 'order_number'
    },
    supplierId: {
      type: INTEGER,
      allowNull: false,
      field: 'supplier_id'
    },
    shopName: {
      type: STRING(200),
      allowNull: true,
      field: 'shop_name'
    },
    purchaser: {
      type: STRING(50),
      allowNull: true
    },
    orderDate: {
      type: DATE,
      allowNull: false,
      field: 'order_date'
    },
    expectedDeliveryDate: {
      type: DATE,
      allowNull: true,
      field: 'expected_delivery_date'
    },
    totalAmount: {
      type: DECIMAL(15, 2),
      allowNull: false,
      field: 'total_amount'
    },
    status: {
      type: STRING(20),
      defaultValue: 'pending',
      allowNull: false
    },
    remark: {
      type: TEXT,
      allowNull: true
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'purchase_orders',
    timestamps: true
  });

  // 关联关系
  PurchaseOrder.associate = function() {
    // 与供应商关联
    PurchaseOrder.belongsTo(app.model.SupplierModel, {
      foreignKey: 'supplierId',
      as: 'supplier'
    });
    
    // 与组织关联
    PurchaseOrder.belongsTo(app.model.OrganizationModel, {
      foreignKey: 'organizationId',
      as: 'organization'
    });
  };

  return PurchaseOrder;
};